<template>
    <div class="song-audio">
        <audio id="player" autoplay controls @ended="ended"></audio>
    </div>
</template>
   
<script>
// mapGetters可以监控store中的值
import { mapGetters } from 'vuex';
export default {
    name: 'song-audio',
    computed: {
        ...mapGetters([
            'url',
            'isPlay'
        ])
    },
    watch: {
        // 监听播放还是暂停状态
        isPlay: function () {
            this.togglePlay();
        }
    },
    methods: {
        // 播放完触发
        ended() {
            this.isPlay = false;
        },
        // 开始暂停切换
        togglePlay() {
            let player = document.querySelector('audio');
            // 换歌给src自动从头播放
            if (player.src !== this.url) {
                player.src = this.url;
                return;
            }
            // 不换歌暂停继续切换
            this.isPlay ? player.play() : player.pause();
        }
    },
}

</script>

<style scoped>
.song-audio {
    display: none;
}
</style>